package vashion.azeroth.core.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vashion.azeroth.checkKeyWord.RabbishCheckUtils;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.PublishFilesErrorEnum;
import vashion.azeroth.contant.experience.ExperienceValue;
import vashion.azeroth.core.manager.personal.PersonalFollowManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.manager.personal.PersonalMemberVipManager;
import vashion.azeroth.core.manager.personal.PersonalPublishFilesManager;
import vashion.azeroth.core.personal.pojo.FeedTag;
import vashion.azeroth.core.personal.pojo.PersonalApproval;
import vashion.azeroth.core.personal.pojo.PersonalExperience;
import vashion.azeroth.core.personal.pojo.PersonalFeed;
import vashion.azeroth.core.personal.pojo.PersonalFeedTags;
import vashion.azeroth.core.personal.pojo.PersonalFollow;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.pojo.PersonalMemberVip;
import vashion.azeroth.core.personal.pojo.PersonalPublishFiles;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.PersonalApprovalService;
import vashion.azeroth.core.service.PersonalCommentService;
import vashion.azeroth.core.service.PersonalExperienceService;
//import vashion.azeroth.core.service.PersonalCommentService;
import vashion.azeroth.core.service.PersonalFavoritesService;
import vashion.azeroth.core.service.PersonalFollowService;
import vashion.azeroth.core.service.PersonalPublishFilesService;
import vashion.azeroth.core.service.base.BaseService;

@Service
public class PersonalPublishFilesServiceImpl<T> extends BaseService implements
        PersonalPublishFilesService<T> {
	
	private static final String DEF_NICK = "vashion小伙伴";

    private final static Logger log = LoggerFactory
            .getLogger(PersonalPublishFilesServiceImpl.class);

    @Autowired
    private PersonalPublishFilesManager personalPublishFilesManager;

    @Autowired
    PersonalFollowManager personalFollowManager;

    @Autowired
    private PersonalFollowService<T> personalFollowService;

    @Autowired
    private PersonalMemberManager personalMemberManager;

    @Autowired
    private PersonalApprovalService<?> personalApprovalService;

    @Autowired
    private PersonalFavoritesService<?> personalFavoritesService;

    @Autowired
    private PersonalCommentService<?> personalCommentService;

    @Autowired
    private PersonalMemberVipManager personalMemberVipManager;
    
	@Autowired
	private PersonalExperienceService<T> personalExperienceService;

    public ApiResult<ArrayList<PersonalPublishFiles>> addFile(
            PersonalPublishFiles publishFiles) {
        ApiResult<ArrayList<PersonalPublishFiles>> result = new ApiResult<ArrayList<PersonalPublishFiles>>();

        // 关键词过滤
		String filterContent = RabbishCheckUtils.filter(publishFiles.getContent());
		publishFiles.setContent(filterContent);

        if (StringUtils.isBlank(publishFiles.getMemberName())) {
            publishFiles.setMemberName(personalMemberManager.get(
                    publishFiles.getMemberId()).getMemberName());
        }

        publishFiles.setTimeAdd(new Date(System.currentTimeMillis()));
        publishFiles.setTimeEdit(new Date(System.currentTimeMillis()));
        publishFiles.setStatus(1);
        PersonalPublishFiles addRes = null;

        ArrayList<String> itemArrayList = PersonalFeedTags.getItemIdsByTags(publishFiles);
        publishFiles.setItemInfo(itemArrayList.toString());
        
        addRes = personalPublishFilesManager.save(publishFiles);

        ArrayList<PersonalPublishFiles> recommendFeeds = null;

        if (null != addRes) {
            publishFiles.setPageSize(4);
            recommendFeeds = personalPublishFilesManager.getFiles(publishFiles);
            
//          发帖成功更新经验值
            PersonalExperience experience = new PersonalExperience();
            experience.setValueBase(ExperienceValue.FEED_PUBLISH_UP.getCode());
			experience.setMemberId(publishFiles.getMemberId());
			try {
				ApiResult<Integer> expRes = personalExperienceService.updateExperienceBase(experience);
				log.info("addFile 帖子发布者更新后经验值为： " + expRes.getData());
			} catch (Exception e) {
				log.error("addFile 更新帖子发布者经验值失败" + e);
			}
			
        }
        result = ApiResult.newSuccessResult(recommendFeeds);
        return result;
    }

    public List<PersonalPublishFiles> find(PersonalPublishFiles publishFiles) {
        return personalPublishFilesManager.find(publishFiles);
    }

    /**
     * 按关注的人获取帖子（我关注的人发的帖子）
     */

    public ApiResult<ArrayList<PersonalFeed>> getFilesByFollower(
            PersonalPublishFiles files, Integer totalcount) {

        ApiResult<ArrayList<PersonalFeed>> result = new ApiResult<ArrayList<PersonalFeed>>();
        try {

            if (files.getSortFlag() == 2) {
                ArrayList<PersonalPublishFiles> followUserFileList = new ArrayList<PersonalPublishFiles>();
                ArrayList<PersonalFeed> feedList = new ArrayList<PersonalFeed>();
                ArrayList<Long> memberIdList = getFansMemberIds(files);

                if (memberIdList.size() == 0) { // 校验如果所有关注的人都未发布文章情况,
                    return ApiResult.newErrorResult(
                            PublishFilesErrorEnum.MY_FOLLOWER_FILES_NULL
                                    .getErrorCode(),
                            PublishFilesErrorEnum.MY_FOLLOWER_FILES_NULL
                                    .getErrorMessage());
                }

                     followUserFileList = personalPublishFilesManager.getFilesByMyFollowUser(files);
                    
                    if (null == followUserFileList || followUserFileList.size() == 0) {
                    	log.error("关注的人未发布过文章。");
                        return ApiResult.newErrorResult(
                                PublishFilesErrorEnum.MY_FOLLOWER_FILES_NULL
                                        .getErrorCode(),
                                PublishFilesErrorEnum.MY_FOLLOWER_FILES_NULL
                                        .getErrorMessage());
					}
                    
                Integer type = 2;
                for (int i = 0; i < followUserFileList.size(); i++) {
                    PersonalFeed feed = new PersonalFeed();
                    String fileId = String.valueOf(followUserFileList.get(i).getPublishFileId());
                    ApiResult<Boolean> appStauts = personalApprovalService.queryIsApproval(files.getMemberId(), type, fileId);

                    if (appStauts.getData().booleanValue()) {
                        followUserFileList.get(i).setApprovalStatus(1);
                    } else {
                        followUserFileList.get(i).setApprovalStatus(0);
                    }

                    ApiResult<Boolean> favStauts = personalFavoritesService.queryIsFavorited(files.getMemberId(), type, fileId);

                    if (favStauts.getData().booleanValue()) {
                        followUserFileList.get(i).setFavoriteStatus(1);
                    } else {
                        followUserFileList.get(i).setFavoriteStatus(0);
                    }

                    feed = getFeed(followUserFileList.get(i));

                    PersonalMemberVip pmv = personalMemberVipManager.get(followUserFileList.get(i).getMemberId());
                    
                    if (null == pmv || null == pmv.getVipLevel()) {
                        feed.setVipLevel("0");
                    } else {
                        feed.setVipLevel(pmv.getVipLevel());
                    }

//                  FollowRelation -- 0：未关注； 1：已关注； 2：相互关注； 3：自已
//                  因为是关注的人的帖子，则关注关注都为1或者2
                    if (followUserFileList.get(i).getMemberId() == files.getMemberId()) {
                        feed.setFollowRelation(3);
                    } else {
                        ApiResult<Integer> isfo = personalFollowService.isFollowed(files.getMemberId(),followUserFileList.get(i).getMemberId());

                        feed.setFollowRelation(isfo.getData());
                    }

                    
                    PersonalMember resMember = personalMemberManager.get(followUserFileList.get(i).getMemberId());
                    String imgHead = resMember.getHeadImg();
                    feed.setHeadImg(imgHead);
                    String nickName = resMember.getNickName();
                    String memberName = resMember.getMemberName();
                    if (nickName.equals(memberName) && nickName.length() == 11) {
                    	feed.setNick(DEF_NICK);
    				}else {
    					feed.setNick(nickName);
					}
                    
                    ApiResult<List<PersonalApproval>> approvalRes = personalApprovalService
                            .getFeedsApprovalInfo(type, fileId);
                    List<String> approersImg = new ArrayList<String>();
                    if (null == approvalRes.getData()) {
                        approersImg.add("");
                        feedList.add(feed);
                        continue;
                    }
                    if (approvalRes.getData().size() > 0) {
                        for (int j = 0; j < approvalRes.getData().size(); j++) {
                            approersImg.add(personalMemberManager.get(
                                    approvalRes.getData().get(j).getMemberId())
                                    .getHeadImg());
                        }
                    }
                    feed.setApproersImg(approersImg);

                    feedList.add(feed);
                }
                return ApiResult.newSuccessResult(feedList, totalcount);
            }

        } catch (Exception e) {
            log.error("getFilesByFollower 获取标签帖子异常",e);
        }
        return result;
    }

    public ArrayList<Long> getFansMemberIds(PersonalPublishFiles files) {

        ArrayList<Long> memberIdList = new ArrayList<Long>();
        PersonalFollow pf = new PersonalFollow();
        try {
            pf.setFansMemberId(files.getMemberId());
            pf.setStatus(1);
            pf.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.NORMAL);

            List<PersonalFollow> personalFansList = personalFollowManager.find(pf);

            for (int i = 0; i < personalFansList.size(); i++) {
                memberIdList.add(personalFansList.get(i).getMemberId());
            }
        } catch (Exception e) {
            log.error("getFansMemberIds 当前帐号未关注作任何人", e);
        }
        return memberIdList;
    }

    /**
     * 按最新获取帖子,时间倒序
     */

    public ApiResult<ArrayList<PersonalFeed>> getFilesByTimeStamp(
            PersonalPublishFiles files, Integer totalCount) {

        ApiResult<ArrayList<PersonalFeed>> result = new ApiResult<ArrayList<PersonalFeed>>();
        ArrayList<PersonalFeed> feedList = new ArrayList<PersonalFeed>();
        try {

            if (files.getSortFlag() == 1) { // 1：获取文章按时间排序，
                // 2：获取文章按精选排序，3：获取文章按关注的人所发表的文章排序
                files.setStatus(1);
                ArrayList<PersonalPublishFiles> timeFileList = personalPublishFilesManager.getFilesByPublishTime(files);  
                		
                if (timeFileList.size() == 0) {
                    return ApiResult.newErrorResult(
                            PublishFilesErrorEnum.MYFILES_NULL.getErrorCode(),
                            PublishFilesErrorEnum.MYFILES_NULL
                                    .getErrorMessage());
                } else {
                    Integer type = 2;
                    
                    if (null != files.getMemberId()) {
                        for (int i = 0; i < timeFileList.size(); i++) {
                            PersonalFeed feed = new PersonalFeed();
                            ApiResult<Boolean> appStauts = personalApprovalService
                                    .queryIsApproval(
                                            files.getMemberId(),
                                            type,
                                            String.valueOf(timeFileList.get(i).getPublishFileId()));
                            if (appStauts.getData().booleanValue()) {
                                timeFileList.get(i).setApprovalStatus(1);
                            } else {
                                timeFileList.get(i).setApprovalStatus(0);
                            }

                            ApiResult<Boolean> favStauts = personalFavoritesService
                                    .queryIsFavorited(
                                            files.getMemberId(),
                                            type,
                                            String.valueOf(timeFileList.get(i).getPublishFileId()));

                            if (favStauts.getData().booleanValue()) {
                                timeFileList.get(i).setFavoriteStatus(1);
                            } else {
                                timeFileList.get(i).setFavoriteStatus(0);
                            }

                            feed = getFeed(timeFileList.get(i));

                            PersonalMemberVip pmv = personalMemberVipManager
                                    .get(timeFileList.get(i).getMemberId());
                            if (null == pmv || null == pmv.getVipLevel()) {
                                feed.setVipLevel("0");
                            } else {
                                feed.setVipLevel(pmv.getVipLevel());
                            }

                            // FollowRelation -- 0：未关注； 1：已关注； 2：自已
                            if (timeFileList.get(i).getMemberId() == files
                                    .getMemberId()) {
                                feed.setFollowRelation(3);
                            } else {
                                ApiResult<Integer> isfo = personalFollowService.isFollowed(files.getMemberId(),timeFileList.get(i).getMemberId());
                                feed.setFollowRelation(isfo.getData());

                            }
                            
                            PersonalMember resMember = personalMemberManager.get(timeFileList.get(i).getMemberId());
                            String imgHead = resMember.getHeadImg();
                            feed.setHeadImg(imgHead);
                            String nickName = resMember.getNickName();
                            String memberName = resMember.getMemberName();
                            if (nickName.equals(memberName) && nickName.length() == 11) {
                            	feed.setNick(DEF_NICK);
							}else {
								feed.setNick(nickName);
							}

                            feed.setCntBrowse(0);// 没有帖子浏览数的更新逻辑

                            ApiResult<List<PersonalApproval>> approvalRes = personalApprovalService
                                    .getFeedsApprovalInfo(type, timeFileList.get(i)
                                            .getPublishFileId().toString());
                            List<String> approersImg = new ArrayList<String>();
                            if (null == approvalRes.getData()) {
                                approersImg.add("");
                                feedList.add(feed);
                                continue;
                            }
                            if (approvalRes.getData().size() > 0) {
                                for (int j = 0; j < approvalRes.getData().size(); j++) {
                                    approersImg.add(personalMemberManager.get(
                                            approvalRes.getData().get(j)
                                                    .getMemberId()).getHeadImg());
                                }
                            }
                            feed.setApproersImg(approersImg);

                            feedList.add(feed);

                        }
					}else {
						for (int j = 0; j < timeFileList.size(); j++) {
							 PersonalFeed feed = new PersonalFeed();
	                         feed = getFeed(timeFileList.get(j));
	                         feedList.add(feed);
						}
					}
                    return ApiResult.newSuccessResult(feedList, totalCount);
                }
            } else {
                log.error("getFilesByTimeStamp 获取帖子失败");
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorMessage());
            }
        } catch (Exception e) {
            log.error("getFilesByTimeStamp 获取帖子异常 ",e);
        }
        return result;
    }

    /**
     * 按精华获取帖子
     * 后台运营置顶接口
     */

    public ApiResult<ArrayList<PersonalFeed>> getFilesByChosen(
            PersonalPublishFiles files, Integer totalCount) {

        ApiResult<ArrayList<PersonalFeed>> result = new ApiResult<ArrayList<PersonalFeed>>();
        ArrayList<PersonalFeed> feedList = new ArrayList<PersonalFeed>();
        try {

            if (files.getSortFlag() == 0) { // 1：获取文章按时间排序，
                // 2：获取文章按精选排序，3：获取文章按关注的人所发表的文章排序
                files.setStatus(2);
                ArrayList<PersonalPublishFiles> timeFileList = personalPublishFilesManager
                        .getFiles(files);
                if (timeFileList.size() == 0) {
                    return ApiResult.newErrorResult(
                            PublishFilesErrorEnum.MYFILES_NULL.getErrorCode(),
                            PublishFilesErrorEnum.MYFILES_NULL
                                    .getErrorMessage());
                } else {
                    Integer type = 2;
                    
                    if (null != files.getMemberId()) {
                    	for (int i = 0; i < timeFileList.size(); i++) {
                            PersonalFeed feed = new PersonalFeed();
                            
                            ApiResult<Boolean> appStauts = personalApprovalService
                                    .queryIsApproval(
                                            files.getMemberId(),
                                            type,
                                            String.valueOf(timeFileList.get(i).getPublishFileId()));

                            if (appStauts.getData().booleanValue()) {
                                timeFileList.get(i).setApprovalStatus(1);
                            } else {
                                timeFileList.get(i).setApprovalStatus(0);
                            }

                            ApiResult<Boolean> favStauts = personalFavoritesService
                                    .queryIsFavorited(
                                            files.getMemberId(),
                                            type,
                                            String.valueOf(timeFileList.get(i).getPublishFileId()));

                            if (favStauts.getData().booleanValue()) {
                                timeFileList.get(i).setFavoriteStatus(1);
                            } else {
                                timeFileList.get(i).setFavoriteStatus(0);
                            }

                            feed = getFeed(timeFileList.get(i));

                            PersonalMemberVip pmv = personalMemberVipManager
                                    .get(timeFileList.get(i).getMemberId());
                            if (null == pmv || null == pmv.getVipLevel()) {
                                feed.setVipLevel("0");
                            } else {
                                feed.setVipLevel(pmv.getVipLevel());
                            }

                            // FollowRelation -- 0：未关注； 1：已关注； 2：相互关注； 3：自已
                            if (timeFileList.get(i).getMemberId() == files
                                    .getMemberId()) {
                                feed.setFollowRelation(3);
                            } else {
                                ApiResult<Integer> isfo = personalFollowService.isFollowed(files.getMemberId(),timeFileList.get(i).getMemberId());

                                feed.setFollowRelation(isfo.getData());

                            }

                            PersonalMember resMember = personalMemberManager.get(timeFileList.get(i).getMemberId());
                            String imghead = resMember.getHeadImg();
                            feed.setHeadImg(imghead);
                            String nickName = resMember.getNickName();
                            String memberName = resMember.getMemberName();
                            if (nickName.equals(memberName) && nickName.length() == 11) {
                            	feed.setNick(DEF_NICK);
							}else {
								feed.setNick(nickName);
							}
                            feed.setCntBrowse(0);// 没有帖子浏览数的更新逻辑

                            ApiResult<List<PersonalApproval>> approvalRes = personalApprovalService
                                    .getFeedsApprovalInfo(type, timeFileList.get(i)
                                            .getPublishFileId().toString());
                            List<String> approersImg = new ArrayList<String>();
                            if (null == approvalRes.getData()) {
                                approersImg.add("");
                                feedList.add(feed);
                                continue;
                            }
                            if (approvalRes.getData().size() > 0) {
                                for (int j = 0; j < approvalRes.getData().size(); j++) {
                                    approersImg.add(personalMemberManager.get(
                                            approvalRes.getData().get(j)
                                                    .getMemberId()).getHeadImg());
                                }
                            }
                            feed.setApproersImg(approersImg);

                            feedList.add(feed);

                        }
					}else {
						
						for (int j = 0; j < timeFileList.size(); j++) {
							PersonalFeed feed = new PersonalFeed();
							feed = getFeed(timeFileList.get(j));
							feedList.add(feed);
						}
					}
                    
                    return ApiResult.newSuccessResult(feedList, totalCount);
                }
            } else {
                log.error("getFilesByChosen 获取精选帖子失败");
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorMessage());
            }
        } catch (Exception e) {
            log.error("getFilesByChosen 获取精选帖子异常",e);
        }
        return result;
    }

    public int findCnt(PersonalPublishFiles files) {
        int count = personalPublishFilesManager.findCnt(files);
        return count;
    }

    public int findCntTimeStamp(PersonalPublishFiles files) {
        int count = personalPublishFilesManager.findCntTimeStamp(files);
        return count;
    }

    public int findCntChosen(PersonalPublishFiles files) {
        int count = personalPublishFilesManager.findCntChosen(files);
        return count;
    }

    public int findCntTags(PersonalPublishFiles files) {
        int count = personalPublishFilesManager.findCntTags(files);
        return count;
    }
    
	@Override
	public Integer cntFilesByMyFollowUser(PersonalPublishFiles files) {
		int count = personalPublishFilesManager.cntFilesByMyFollowUser(files);
		 return count;
	}

    /**
     * 按tag获取帖子
     */

    public ApiResult<ArrayList<PersonalFeed>> getFilesByTags(
            PersonalPublishFiles files, Integer totalCount) {

    	
        ApiResult<ArrayList<PersonalFeed>> result = new ApiResult<ArrayList<PersonalFeed>>();
        ArrayList<PersonalFeed> feedList = new ArrayList<PersonalFeed>();
        try {

            if (files.getSortFlag() == 3) {
                ArrayList<PersonalPublishFiles> timeFileList = personalPublishFilesManager
                        .getFilesByTags(files);
                if (timeFileList.size() == 0) {
                    return ApiResult.newErrorResult(
                            PublishFilesErrorEnum.TAGS_NULL.getErrorCode(),
                            PublishFilesErrorEnum.TAGS_NULL.getErrorMessage());
                } else {
                    Integer type = 2;
                    for (int i = 0; i < timeFileList.size(); i++) {
                        PersonalFeed feed = new PersonalFeed();

                        ApiResult<Boolean> appStauts = personalApprovalService
                                .queryIsApproval(
                                        files.getMemberId(),
                                        type,
                                        String.valueOf(timeFileList.get(i).getPublishFileId()));
                        if (appStauts.getData().booleanValue()) {
                            timeFileList.get(i).setApprovalStatus(1);
                        } else {
                            timeFileList.get(i).setApprovalStatus(0);
                        }

                        ApiResult<Boolean> favStauts = personalFavoritesService
                                .queryIsFavorited(
                                        files.getMemberId(),
                                        type,
                                        String.valueOf(timeFileList.get(i).getPublishFileId()));
                        if (favStauts.getData().booleanValue()) {
                            timeFileList.get(i).setFavoriteStatus(1);
                        } else {
                            timeFileList.get(i).setFavoriteStatus(0);
                        }

                        feed = getFeed(timeFileList.get(i));

                        PersonalMemberVip pmv = personalMemberVipManager
                                .get(timeFileList.get(i).getMemberId());
                        if (null == pmv || null == pmv.getVipLevel()) {
                            feed.setVipLevel("0");
                        } else {
                            feed.setVipLevel(pmv.getVipLevel());
                        }

                        // FollowRelation -- 0：未关注； 1：已关注； 2：相互关注； 3：自已
                        if (timeFileList.get(i).getMemberId() == files
                                .getMemberId()) {
                            feed.setFollowRelation(3);
                        } else {
                            ApiResult<Integer> isfo = personalFollowService.isFollowed(files.getMemberId(),timeFileList.get(i).getMemberId());

                            feed.setFollowRelation(isfo.getData());

                        }
                        
                        PersonalMember resMember = personalMemberManager.get(timeFileList.get(i).getMemberId());
                        String imgHead = resMember.getHeadImg();
                        feed.setHeadImg(imgHead);
                        String nickName = resMember.getNickName();
                        String memberName = resMember.getMemberName();
                        if (nickName.equals(memberName) && nickName.length() == 11) {
                        	feed.setNick(DEF_NICK);
						}else {
							feed.setNick(nickName);
						}
                        
                        feed.setCntBrowse(0);// 没有帖子浏览数的更新逻辑

                        ApiResult<List<PersonalApproval>> approvalRes = personalApprovalService
                                .getFeedsApprovalInfo(type, timeFileList.get(i)
                                        .getPublishFileId().toString());
                        List<String> approersImg = new ArrayList<String>();
                        if (null == approvalRes.getData()) {
                            approersImg.add("");
                            feedList.add(feed);
                            continue;
                        }
                        if (approvalRes.getData().size() > 0) {
                            for (int j = 0; j < approvalRes.getData().size(); j++) {
                                approersImg.add(personalMemberManager.get(
                                        approvalRes.getData().get(j)
                                                .getMemberId()).getHeadImg());
                            }
                        }
                        feed.setApproersImg(approersImg);

                        feedList.add(feed);

                    }
                    return ApiResult.newSuccessResult(feedList, totalCount);
                }
            } else {
                log.error("getFilesByTags 获取标签帖子失败");
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorMessage());
            }
        } catch (Exception e) {
            log.error("getFilesByTags 获取标签帖子异常",e);

        }
        return result;
    }

    public ApiResult<ArrayList<PersonalPublishFiles>> getMyFiles(
            PersonalPublishFiles files, Integer totalCounts) {
        // TODO Auto-generated method stub
        return null;
    }

    public ApiResult<ArrayList<PersonalFeed>> getFilesById(
            PersonalPublishFiles files, Integer totalCount) {

        ApiResult<ArrayList<PersonalFeed>> result = new ApiResult<ArrayList<PersonalFeed>>();
        ArrayList<PersonalFeed> feedList = new ArrayList<PersonalFeed>();
        try {
            ArrayList<PersonalPublishFiles> resFile = personalPublishFilesManager
                    .getFilesById(files);
            if (null == resFile) {
                log.error("getFilesById 获取帖子详情失败");
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorMessage());

            }
            
            PersonalFeed feed;
            Integer type = 2;
            
            if (null != files.getMemberId()) {


                ApiResult<Boolean> appStauts = personalApprovalService
                        .queryIsApproval(
                                files.getMemberId(),
                                type,
                                String.valueOf(resFile.get(0).getPublishFileId()));
                if (appStauts.getData().booleanValue()) {
                    resFile.get(0).setApprovalStatus(1);
                } else {
                    resFile.get(0).setApprovalStatus(0);
                }

                ApiResult<Boolean> favStauts = personalFavoritesService
                        .queryIsFavorited(
                                files.getMemberId(),
                                type,
                                String.valueOf(resFile.get(0).getPublishFileId()));

                if (favStauts.getData().booleanValue()) {
                    resFile.get(0).setFavoriteStatus(1);
                } else {
                    resFile.get(0).setFavoriteStatus(0);
                }

                feed = getFeed(resFile.get(0));

                PersonalMemberVip pmv = personalMemberVipManager.get(resFile.get(0)
                        .getMemberId());
                if (null == pmv || null == pmv.getVipLevel()) {
                    feed.setVipLevel("0");
                } else {
                    feed.setVipLevel(pmv.getVipLevel());
                }

                // FollowRelation -- 0：未关注； 1：已关注； 2：相互关注 3：自已
                if (resFile.get(0).getMemberId() == files.getMemberId()) {
                    feed.setFollowRelation(3);
                } else {
                    ApiResult<Integer> isfo = personalFollowService.isFollowed(files.getMemberId(), resFile.get(0).getMemberId());

                    feed.setFollowRelation(isfo.getData());
                }

                PersonalMember resMember = personalMemberManager.get(resFile.get(0).getMemberId());
                String imgHead = resMember.getHeadImg();
                feed.setHeadImg(imgHead);
                String nickName = resMember.getNickName();
                String memberName = resMember.getMemberName();
                if (nickName.equals(memberName) && nickName.length() == 11) {
                	feed.setNick(DEF_NICK);
				}else {
					feed.setNick(nickName);
				}
                feed.setCntBrowse(0);// 没有帖子浏览数的更新逻辑

                ApiResult<List<PersonalApproval>> approvalRes = personalApprovalService
                        .getFeedsApprovalInfo(type, resFile.get(0)
                                .getPublishFileId().toString());
                List<String> approersImg = new ArrayList<String>();
                if (null == approvalRes.getData()) {
                    approersImg.add("");
                    feedList.add(feed);
                } else {
                    for (int j = 0; j < approvalRes.getData().size(); j++) {
                        approersImg.add(personalMemberManager.get(
                                approvalRes.getData().get(j).getMemberId())
                                .getHeadImg());
                    }

                    feed.setApproersImg(approersImg);

                    feedList.add(feed);
                }
                
			}else {
                    feed = getFeed(resFile.get(0));
                    feed.setNick(DEF_NICK);
                    feedList.add(feed);
				}


            return ApiResult.newSuccessResult(feedList, totalCount);
        } catch (Exception e) {
            log.error("getFilesById 异常" ,e);
        }
        return result;
    }

    public ApiResult<ArrayList<PersonalFeed>> getFilesBymemberId(
            PersonalPublishFiles files, Integer totalCount) {

        ApiResult<ArrayList<PersonalFeed>> result = new ApiResult<ArrayList<PersonalFeed>>();
        ArrayList<PersonalFeed> feedList = new ArrayList<PersonalFeed>();
        try {
            files.setPageSize(100);//取用户的前100条数据
            ArrayList<PersonalPublishFiles> resFile = personalPublishFilesManager
                    .getFilesBymemberId(files);
            if (null == resFile) {
                log.error("getFilesBymemberId 获取帖子详情失败");
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorMessage());
            }
            for (int i = 0; i < resFile.size(); i++) {
                PersonalFeed feed = new PersonalFeed();
                Integer type = 2;

                ApiResult<Boolean> appStauts = personalApprovalService
                        .queryIsApproval(
                                files.getMemberId(),
                                type,
                                String.valueOf(resFile.get(i).getPublishFileId()));
                if (appStauts.getData().booleanValue()) {
                    resFile.get(i).setApprovalStatus(1);
                } else {
                    resFile.get(i).setApprovalStatus(0);
                }

                ApiResult<Boolean> favStauts = personalFavoritesService
                        .queryIsFavorited(
                                files.getMemberId(),
                                type,
                                String.valueOf(resFile.get(i).getPublishFileId()));

                if (favStauts.getData().booleanValue()) {
                    resFile.get(i).setFavoriteStatus(1);
                } else {
                    resFile.get(i).setFavoriteStatus(0);
                }

                feed = getFeed(resFile.get(i));

                PersonalMemberVip pmv = personalMemberVipManager.get(resFile
                        .get(i).getMemberId());
                if (null == pmv || null == pmv.getVipLevel()) {
                    feed.setVipLevel("0");
                } else {
                    feed.setVipLevel(pmv.getVipLevel());
                }

                // FollowRelation -- 0：未关注； 1：已关注； 2：相互关注； 3：自已
                if (resFile.get(i).getMemberId() == files.getMemberId()) {
                    feed.setFollowRelation(3);
                } else {
                    ApiResult<Integer> isfo = personalFollowService.isFollowed(files.getMemberId(), resFile.get(i).getMemberId());
                    feed.setFollowRelation(isfo.getData());
                }
                
                PersonalMember resMember = personalMemberManager.get(resFile.get(i).getMemberId());
                String imgHead = resMember.getHeadImg();
                feed.setHeadImg(imgHead);
                String nickName = resMember.getNickName();
                String memberName = resMember.getMemberName();
                if (nickName.equals(memberName) && nickName.length() == 11) {
                	feed.setNick(DEF_NICK);
				}else {
					feed.setNick(nickName);
				}

                feed.setCntBrowse(0);// 没有帖子浏览数的更新逻辑

                ApiResult<List<PersonalApproval>> approvalRes = personalApprovalService
                        .getFeedsApprovalInfo(type, resFile.get(i)
                                .getPublishFileId().toString());
                List<String> approersImg = new ArrayList<String>();
                if (null == approvalRes.getData()) {
                    approersImg.add("");
                    feedList.add(feed);
                    continue;
                }
                if (approvalRes.getData().size() > 0) {
                    for (int j = 0; j < approvalRes.getData().size(); j++) {
                        approersImg.add(personalMemberManager.get(
                                approvalRes.getData().get(j).getMemberId())
                                .getHeadImg());
                    }
                }
                feed.setApproersImg(approersImg);

                feedList.add(feed);

            }
            result = ApiResult.newSuccessResult(feedList, totalCount);
        } catch (Exception e) {
            log.error("getFilesBymemberId 获取帖子异常",e);
        }
        return result;
    }

    /**
     * 给小漠漠提供：根据用户id，获取这个用户发表的带有商品id的帖子列表
     */

    public ApiResult<Map<Integer, PersonalPublishFiles>> getFeedIdByTags(
            PersonalPublishFiles files, Integer totalCount) {

        ApiResult<Map<Integer, PersonalPublishFiles>> result = new ApiResult<Map<Integer, PersonalPublishFiles>>();
        Map<Integer, PersonalPublishFiles> feedList = Maps.newHashMap();
        try {
            files.setPageSize(100);
            ArrayList<PersonalPublishFiles> resFile = personalPublishFilesManager
                    .getFilesBymemberId(files);
            if (null == resFile) {
                log.error("getFeedIdByTags 获取帖子详情失败");
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorMessage());
            }
            for (int i = 0; i < resFile.size(); i++) {
                String tags = resFile.get(i).getTags();
                ObjectMapper mapper = new ObjectMapper();
                FeedTag[] feedTags = mapper.readValue(tags, FeedTag[].class);
                for (int j = 0; j < feedTags.length; j++) {
                    if (feedTags[j].getGoodID().equals("")) {
                        continue;
                    } else {
                        feedList.put(resFile.get(i).getPublishFileId().intValue(), resFile.get(i));
                    }
                }
            }
            totalCount = feedList.size();
            result = ApiResult.newSuccessResult(feedList, totalCount);
        } catch (Exception e) {
            log.error("getFeedIdByTags 获取帖子异常",e);
        }
        return result;
    }


    /**
     * 给金宝提供：根据贴子Id获取商品ID接口
     */

    public ApiResult<ArrayList<Integer>> getItemIdByFeedId(
            PersonalPublishFiles files, Integer totalCount) {

        ApiResult<ArrayList<Integer>> result = new ApiResult<ArrayList<Integer>>();
        ArrayList<Integer> itemIdList = new ArrayList<Integer>();
        try {
            files.setPageSize(100);
            ArrayList<PersonalPublishFiles> resFile = personalPublishFilesManager.getFilesById(files);
            if (null == resFile) {
                log.error("getItemIdByFeedId 获取帖子详情失败");
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.GET_FILES_FAIL.getErrorMessage());
            }
            for (int i = 0; i < resFile.size(); i++) {
                String tags = resFile.get(i).getTags();
                ObjectMapper mapper = new ObjectMapper();
                FeedTag[] feedTags = mapper.readValue(tags, FeedTag[].class);
                for (int j = 0; j < feedTags.length; j++) {
                    if (feedTags[j].getGoodID().equals("")) {
                        continue;
                    } else {
                        itemIdList.add(Integer.valueOf(feedTags[j].getGoodID()));
                    }
                }
            }

            if (itemIdList.size() == 0) {
                return ApiResult.newErrorResult(PublishFilesErrorEnum.ITEM_NULL.getErrorCode(), PublishFilesErrorEnum.ITEM_NULL.getErrorMessage());
            }
            totalCount = itemIdList.size();
            result = ApiResult.newSuccessResult(itemIdList, totalCount);
        } catch (Exception e) {
            log.error("getItemIdByFeedId 获取帖子异常",e);
        }
        return result;
    }


    public Integer findCntMembers(PersonalPublishFiles files) {
        int count = personalPublishFilesManager.findCntMembers(files);
        return count;
    }

    public PersonalFeed getFeed(PersonalPublishFiles files) {
        PersonalFeed feed = new PersonalFeed();
        feed.setApprovalCount(files.getApprovalCount());
        feed.setCommentCount(files.getCommentCount());
        feed.setContactLabelRange(files.getContactLabelRange());
        feed.setContent(files.getContent());
        feed.setCoordinateAddress(files.getCoordinateAddress());
        feed.setFavoriteCount(files.getFavoriteCount());
        feed.setFeedPic(files.getFeedPic());
        feed.setFirstRow(files.getFirstRow());
        feed.setMemberId(files.getMemberId());
        feed.setMemberName(files.getMemberName());
        feed.setPageNum(files.getPageNum());
        feed.setPageSize(files.getPageSize());
        feed.setPosFlag(files.getPosFlag());
        feed.setPosx(files.getPosx());
        feed.setPosy(files.getPosy());
        feed.setPublishFileId(files.getPublishFileId());
        feed.setRemark(files.getRemark());
        feed.setSortFlag(files.getSortFlag());
        feed.setStatus(files.getStatus());
        feed.setApprovalStatus(files.getApprovalStatus());
        feed.setFavoriteStatus(files.getFavoriteStatus());

        ArrayList<FeedTag> feedTags = new ArrayList<FeedTag>();
        if (files.getTags().equals("[]")) {
            feed.setTags(new ArrayList<FeedTag>());
        } else {
            ObjectMapper mapper = new ObjectMapper();
            try {
                FeedTag[] feedTag = mapper.readValue(files.getTags(), FeedTag[].class);
                for (int i = 0; i < feedTag.length; i++) {
                    feedTags.add(feedTag[i]);
                }
                feed.setTags(feedTags);
            } catch (Exception e) {
                log.error("getFeed 异常",e);
            }
        }

        feed.setTimeAdd(files.getTimeAdd());
        feed.setTimeEdit(files.getTimeEdit());
        feed.setTitle(files.getTitle());

        return feed;
    }

	@Override
	public ApiResult<Boolean> updateFeedsForChosen(PersonalPublishFiles files,
			Integer totalCounts) {
		int updateFiles = 0;
		ApiResult<Boolean> result = new ApiResult<Boolean>();
		try {
	    	ArrayList<PersonalPublishFiles> resFiles = personalPublishFilesManager.getFilesById(files);
			Long memberId = resFiles.get(0).getMemberId();
			
			updateFiles = personalPublishFilesManager
					.updateFeedsForChosen(files);
			
			if (updateFiles == 1) {
				result = ApiResult.newSuccessResult(Boolean.valueOf(true),
						totalCounts);

				// 发帖成功更新经验值, 经验值+100
				PersonalExperience experience = new PersonalExperience();
				experience.setValueBase(ExperienceValue.FEED_CHOSEN_UP
						.getCode());
				experience.setMemberId(memberId);
				try {
					ApiResult<Integer> expRes = personalExperienceService
							.updateExperienceBase(experience);
					log.info("帖子被精选，帖子发布者更新后经验值为： " + expRes.getData());
				} catch (Exception e) {
					log.error("帖子被精选，更新帖子发布者经验值失败" + e);
				}

			} else {
				return ApiResult.newErrorResult(
						PublishFilesErrorEnum.CHOSEN_FILES_FAIL.getErrorCode(),
						PublishFilesErrorEnum.CHOSEN_FILES_FAIL
								.getErrorMessage());
			}

		} catch (Exception e) {
			log.error("updateFeedsForChosen 获取帖子异常", e);
		}
		return result;
	}


    @Override
    public ApiResult<Boolean> deleteFeedsByPublishFileId(
            PersonalPublishFiles files, Integer totalCounts,
            Long actionMemberId) {
        int updateFiles;
        ApiResult<Boolean> result = new ApiResult<Boolean>();
        try {

            if (null == actionMemberId || 0 == actionMemberId) {
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.ACTION_MEMBERID_NULL
                                .getErrorCode(),
                        PublishFilesErrorEnum.ACTION_MEMBERID_NULL
                                .getErrorMessage());
            } else {

            	// 只要能拿到memberid，就默认有权限删除
                // 后台用户删除
                updateFiles = personalPublishFilesManager
                        .deleteFeedsByPublishFileId(files);
            }

            if (updateFiles == 1) {
                result = ApiResult.newSuccessResult(Boolean.valueOf(true),
                        totalCounts);

            } else {
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.DELETE_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.DELETE_FILES_FAIL
                                .getErrorMessage());
            }

        } catch (Exception e) {
            log.error("deleteFeedsByPublishFileId 删除帖子异常",e);
        }
        return result;
    }

    @Override
    public ApiResult<Boolean> restoreFeedsByPublishFileId(PersonalPublishFiles files,
                                                          Integer totalCounts) {
        int updateFiles;
        ApiResult<Boolean> result = new ApiResult<Boolean>();
        try {
            updateFiles = personalPublishFilesManager.restoreFeedsByPublishFileId(files);

            if (updateFiles == 1) {
                result = ApiResult.newSuccessResult(Boolean.valueOf(true),
                        totalCounts);

            } else {
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.RESTORE_FILES_FAIL.getErrorCode(),
                        PublishFilesErrorEnum.RESTORE_FILES_FAIL
                                .getErrorMessage());
            }

        } catch (Exception e) {
            log.error("restoreFeedsByPublishFileId 还原帖子异常",e);
        }
        return result;
    }

    /**
     * 查询帖子状态，
     * true： 帖子被置顶
     * false：帖子未被置顶
     */

    @Override
    public ApiResult<Integer> queryFeedStatus(PersonalPublishFiles files,
                                              Integer totalCounts) {
        ApiResult<Integer> result = new ApiResult<Integer>();
        PersonalPublishFiles resFiles;
        try {
            resFiles = personalPublishFilesManager.queryFeedStatus(files);

            if (resFiles.getStatus() == 2) {
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.FEED_CHOSEN.getErrorCode(),
                        PublishFilesErrorEnum.FEED_CHOSEN.getErrorMessage());

            } else if (resFiles.getStatus() == 0) {
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.FEED_DELETE.getErrorCode(),
                        PublishFilesErrorEnum.FEED_DELETE.getErrorMessage());
            } else {
                return ApiResult.newErrorResult(
                        PublishFilesErrorEnum.FEED_NORMAL.getErrorCode(),
                        PublishFilesErrorEnum.FEED_NORMAL.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("queryFeedStatus 查询帖子状态异常",e);
        }
        return result;
    }

}
